package com.ls.netty.peotocoltcp.client;

import com.ls.netty.peotocoltcp.MessageProtocol;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;

public class MyCIientHandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count;

    //当通道就绪是就会触发该方法
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("发送数据");
        //客户端发送10条数据
        for (int i = 0; i < 10; i++) {
            String message = "外交部评中美高层战略对话成果";
            byte[] bytes = message.getBytes(Charset.forName("utf-8"));
            int length = bytes.length;
            MessageProtocol mp = new MessageProtocol(length, bytes);
            ctx.writeAndFlush(mp);
        }

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {


    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("客户端发生异常" + cause.getMessage());
        ctx.close();
    }
}
